import { Component } from '@angular/core';
import { IonicPage, NavController, NavParams, AlertCmp, AlertController } from 'ionic-angular';
import { NetProvider } from '../../providers/net/net';
import { GlobalsProvider } from '../../providers/globals/globals';
import { MenuPage } from '../menu/menu';
import { StorageProvider } from '../../providers/storage/storage';


/**
 * Generated class for the LoginPage page.
 *
 * See https://ionicframework.com/docs/components/#navigation for more info on
 * Ionic pages and navigation.
 */

@IonicPage()
@Component({
  selector: 'page-login',
  templateUrl: 'login.html',
})
export class LoginPage {

  public username: string;
  public password: string;

  constructor(public navCtrl: NavController, public navParams: NavParams, private net: NetProvider, private globals: GlobalsProvider, public alertCtrl: AlertController, public store: StorageProvider) {
  }

  ionViewDidLoad() {

  }

  submit() {
    let me = this;
    this.net.post(this.globals.urls.login, { username: this.username, password: this.password }, (data) => {
      if (data && data.code) {
        if (data.code == "200") {
          me.globals.authToken = data.data;
          me.store.store("X-AUTH-TOKEN", data.data);
          me.globals.navControl.setRoot(MenuPage);
        } else if (data.code == "401") {
          const alert = this.alertCtrl.create({
            title: '提示',
            subTitle: '登录失败',
            buttons: ['确定']
          });
          alert.present();
        }
      }
    }, (x) => {
    });
  }

  rest() {
    this.username = '';
    this.password = '';
  }

}
